#!/bin/bash

# 服务器WebSocket连接测试脚本
# 使用方法: ./test-server.sh

SERVER_IP="180.184.50.86"
PORT="8083"
WS_URL="ws://${SERVER_IP}:${PORT}/ws"

echo "=== WebSocket服务器测试 ==="
echo "服务器: ${SERVER_IP}:${PORT}"
echo "WebSocket URL: ${WS_URL}"
echo ""

# 1. 检查Docker容器状态
echo "1. 检查Docker容器状态..."
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
echo ""

# 2. 检查端口监听
echo "2. 检查端口监听状态..."
netstat -tlnp | grep ${PORT} || echo "端口 ${PORT} 未监听"
echo ""

# 3. 测试HTTP连接
echo "3. 测试HTTP连接..."
curl -I http://localhost:${PORT} 2>/dev/null && echo "✅ HTTP连接正常" || echo "❌ HTTP连接失败"
echo ""

# 4. 检查防火墙状态
echo "4. 检查防火墙状态..."
if command -v ufw &> /dev/null; then
    echo "UFW状态:"
    sudo ufw status | grep ${PORT} || echo "端口 ${PORT} 未在UFW中开放"
elif command -v firewall-cmd &> /dev/null; then
    echo "Firewalld状态:"
    sudo firewall-cmd --list-ports | grep ${PORT} || echo "端口 ${PORT} 未在firewalld中开放"
else
    echo "未检测到防火墙管理工具"
fi
echo ""

# 5. 查看应用日志
echo "5. 查看应用日志（最近10行）..."
docker compose -f docker-compose.publish.yml logs --tail=10
echo ""

# 6. 使用websocat测试WebSocket连接（如果安装了）
echo "6. 测试WebSocket连接..."
if command -v websocat &> /dev/null; then
    echo "使用websocat测试连接..."
    timeout 5 websocat ${WS_URL} <<< '{"Type":"register","Username":"testuser","Content":"","Timestamp":"'$(date -Iseconds)'"}' || echo "WebSocket连接测试失败"
elif command -v wscat &> /dev/null; then
    echo "使用wscat测试连接..."
    timeout 5 wscat -c ${WS_URL} -x '{"Type":"register","Username":"testuser","Content":"","Timestamp":"'$(date -Iseconds)'"}' || echo "WebSocket连接测试失败"
else
    echo "未安装WebSocket测试工具 (websocat 或 wscat)"
    echo "可以安装: npm install -g wscat 或下载 websocat"
fi
echo ""

echo "=== 测试完成 ==="
echo ""
echo "如果发现问题，请尝试以下解决方案："
echo "1. 重启服务: docker compose -f docker-compose.publish.yml restart"
echo "2. 开放防火墙端口: sudo ufw allow ${PORT} 或 sudo firewall-cmd --permanent --add-port=${PORT}/tcp"
echo "3. 检查云服务商安全组设置"
echo "4. 查看详细日志: docker compose -f docker-compose.publish.yml logs -f"